package cn.wolfcode.trip.base.util;

import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.io.Resources;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.UUID;

/**
 * 文件上传工具
 */
public abstract class UploadUtil {

	public static String imgDir;

	static {
		try {
			InputStream in = Resources.getResourceAsStream("dir.properties");
			Properties p = new Properties();
			p.load(in);
			imgDir = p.getProperty("dirPath");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 处理文件上传
	 * @param file
	 * @return
	 */
	public static String upload(MultipartFile file) {
		String uuid = UUID.randomUUID().toString();

		String orgFileName = file.getOriginalFilename();
		String ext= "." + FilenameUtils.getExtension(orgFileName);
		String fileName = uuid + ext;
		try {
			Files.write(Paths.get(imgDir, fileName), file.getBytes());
			return "/upload/"+fileName;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
























